package com.xhwl.logistics.util;

import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @Author： lianghz
 * @Description： 上传工具类
 * @Date 2021/10/18/ 14:39
 */
//@Component
@Slf4j
public class UploadUtils {

   /* @Autowired
    private IObsService obsService;*/

    public String uploadImgBase64(String imgBase64) {
        String url = null;
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] bytes = decoder.decode(imgBase64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            InputStream inputStream = new ByteArrayInputStream(bytes);
            //url = SpringContextUtils.getBean(IObsService.class).uploadImg(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 当链接地址的密钥比较奇怪时，先调用这个方法
     */
    public static void slovePKIX() throws Exception {
        trustAllHttpsCertificates();
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

    private static HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
            return true;
        }
    };

    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    private static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
            return;
        }
    }

    /**
     * 私有图片资源转换为公有云资源
     *
     * @throws Exception
     */
    public static  synchronized   String uploadImg(String pictureUrl) {
        InputStream inputStream = null;
        String picUrl;
        ByteArrayOutputStream outStream = null;
        FileOutputStream op = null;
        try {
            // 构造URL
            URL url = new URL(pictureUrl);
            // 打开连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //通过输入流获取图片数据
            inputStream = conn.getInputStream();
            //用这个做中转站 ，把图片数据都放在了这里，再调用toByteArray()即可获得数据的byte数组
            outStream = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            //读取图片数据
            while ((len = inputStream.read(buf)) != -1) {
                //System.out.println(len);
                outStream.write(buf, 0, len);
            }
            //把图片数据填入文件中
            File file = new File("pictureUrl.jpg");
            op = new FileOutputStream(file);
            op.write(outStream.toByteArray());
            //picUrl = SpringContextUtils.getBean(IObsService.class).uploadImg(file);

        } catch (Exception e) {
            throw new RuntimeException("Failed to upload image," + e.getMessage());
        } finally {
            if (inputStream != null) {
                // 完毕，关闭所有链接
                try {
                    op.close();
                    outStream.close();
                    inputStream.close();
                } catch (Exception e) {
                    throw new RuntimeException("Failed close all links," + e.getMessage());
                }
            }
        }
        //return picUrl;
        return null;
    }

}
